package com.codebox.knowledge.x5webview;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.codebox.common.common.RouterPath;
import com.codebox.knowledge.R;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

@Route(path = RouterPath.KnowledgeRouterPath.PATH_TBS)
public class TbsActivity extends AppCompatActivity implements ValueCallback<String>, QbSdk.PreInitCallback {

    String testFile = "/storage/emulated/0/报价单.docx";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tbs);

        initView();
        initData();
    }

    private void initView() {
        Button btnOpen = findViewById(R.id.btn_open);
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "open file", Toast.LENGTH_SHORT).show();
                openFileReader(v.getContext(), testFile);
            }
        });

        makeRootDirectory("/wanandroid/");
    }

    private void initData() {
        QbSdk.initX5Environment(this, this);

        String mFilePath = Environment.getExternalStorageDirectory().toString();

        Log.e("test", mFilePath);

    }


    public void openFileReader(Context context, String pathName) {

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("local", "true");
        JSONObject Object = new JSONObject();
        try {
            Object.put("pkgName", context.getApplicationContext().getPackageName());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("menuData", Object.toString());
        QbSdk.getMiniQBVersion(context);
        int ret = QbSdk.openFileReader(context, pathName, params, this);

    }

    @Override
    public void onCoreInitFinished() {
        Log.d("test", "onCoreInitFinished");
    }

    @Override
    public void onViewInitFinished(boolean b) {
        Log.d("test", "onViewInitFinished,isX5Core =" + b);
    }

    @Override
    public void onReceiveValue(String s) {
        Log.d("test", "onReceiveValue,val =" + s);
    }


    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }
}
